package com.szgd.service.vehicle;

import com.szgd.dao.ecdata.vehicle.VehicleEnterExitMapper;
import com.szgd.paging.Order;
import com.szgd.paging.PageBounds;
import com.szgd.service.gatherEquip.GatherEquipService;
import com.szgd.service.personnel.EnterExitService;
import com.szgd.service.sys.SimulateBaseService;
import com.szgd.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class VehicleEnterExitService extends SimulateBaseService {
    @Autowired
    VehicleEnterExitMapper vehicleEnterExitMapper;
    @Autowired
    VehicleService vehicleService;
    @Autowired
    GatherEquipService gatherEquipService;

    private static Logger logger = Logger.getLogger(EnterExitService.class);
    public void synVehicleEnterExitRecord(String vehicleId,String plateNumber,String plateType,String plateColor,String vehicleBrand,String vehicleColor,
                                          String vehicleSize,String ip,String passTime,String name, String path){
        logger.info("开始同步车辆进入闸机数据!");

        List<Map<String, Object>>  gatherEquipList = gatherEquipService.getVehicleGatherEquipList();

        if (gatherEquipList.size()==0)
            return;
        int i = 0;
        for (; i < gatherEquipList.size(); i++) {//循环同步进入闸机记录
            Map<String, Object> gatherEquipMap = gatherEquipList.get(i);
            String tempIp = gatherEquipMap.get("ip").toString();
            if (tempIp.equalsIgnoreCase(ip))
            {
                String projectId = gatherEquipMap.get("projectId")==null?"":gatherEquipMap.get("projectId").toString();
                String workSiteId = gatherEquipMap.get("workSiteId")==null?"":gatherEquipMap.get("workSiteId").toString();
                String siteId = gatherEquipMap.get("siteId")==null?"":gatherEquipMap.get("siteId").toString();
                String gatherEquipId = gatherEquipMap.get("id").toString();
                int passFlag  = Integer.parseInt(gatherEquipMap.get("passFlag").toString());
                boolean result = insertVehicleEnterExitFromOtherSystem(vehicleId,passFlag,projectId,workSiteId,siteId,gatherEquipId,plateNumber,plateType,
                        plateColor,  vehicleBrand,  vehicleColor, vehicleSize,passTime,name,path);
                System.out.println(result?"同步车辆进出记录成功!":"同步车辆进出记录失败!");
                logger.info(result?"同步车辆进出记录成功!":"同步车辆进出记录失败!");
                break;
            }
        }
        if (i==gatherEquipList.size())
        {
            logger.info("在系统采集设备表中未找到IP是"+ip+" 的设备！");
        }
        logger.info("结束同步车辆进入闸机数据!");

    }

    /**
     * 从其他系统数据插入
     */
    public  boolean insertVehicleEnterExitFromOtherSystem(String vehicleId,int passFlag,String projectId, String workSiteId,String siteId,String gatherEquipId,
                                                      String plateNumber,String plateType,String plateColor,String vehicleBrand,String vehicleColor,String vehicleSize,String passTime,String name, String path)
    {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("passFlag",passFlag);
        paramsMap.put("vehicleId",vehicleId);
        paramsMap.put("workSiteId",workSiteId);
        paramsMap.put("siteId",siteId);
        paramsMap.put("gatherEquipId",gatherEquipId);
        paramsMap.put("plateNumber",plateNumber);
        paramsMap.put("plateType",plateType);
        paramsMap.put("plateColor",plateColor);
        paramsMap.put("vehicleBrand",vehicleBrand);
        paramsMap.put("vehicleColor",vehicleColor);
        paramsMap.put("vehicleSize",vehicleSize);
        paramsMap.put("passTime",passTime);
        paramsMap.put("name",name);
        paramsMap.put("path",path);

        if (passFlag == 2)//如果是离开闸机，获取上次进入记录ID，保存到此条离开记录
        {
            Map<String, Object> enterParamsMap = new HashMap<>();
            enterParamsMap.put("rownum",1);//获取最新一条
            enterParamsMap.put("plateNumber",plateNumber);
            enterParamsMap.put("passFlag",1);
            enterParamsMap.put("endPassTime",passTime);
            enterParamsMap.put("exitIdIsNull",1);
            enterParamsMap.put("passTimeSort",1);//1降序desc，0升序asc
            enterParamsMap.put("siteId",siteId);
            List<Map<String,Object>> list = vehicleEnterExitMapper.getTopNVehicleEnterOrExitList(enterParamsMap);
            if (list != null && list.size() > 0)
            {
                Map<String,Object> enterRecordMap = list.get(0);
                String enterId = enterRecordMap.get("id").toString();
                paramsMap.put("enterId",enterId);
                paramsMap.put("updateTime",enterRecordMap.get("passTime"));
            }
        }else  if (passFlag == 1)//如果是进入闸机，获取此时间后第一条离开记录ID
        {
            Map<String, Object> enterParamsMap = new HashMap<>();
            enterParamsMap.put("rownum",1);//获取最新一条
            enterParamsMap.put("equipNumber",plateNumber);
            enterParamsMap.put("passFlag",2);
            enterParamsMap.put("beginPassTime",passTime);
            enterParamsMap.put("enterIdIsNull",1);
            enterParamsMap.put("passTimeSort",0);//1降序desc，0升序asc
            enterParamsMap.put("siteId",siteId);
            List<Map<String,Object>> list = vehicleEnterExitMapper.getTopNVehicleEnterOrExitList(enterParamsMap);
            if (list != null && list.size() > 0)
            {
                Map<String,Object> exitRecordMap = list.get(0);
                String exitId = exitRecordMap.get("id").toString();
                paramsMap.put("exitId",exitId);
                paramsMap.put("updateTime",exitRecordMap.get("passTime"));
            }
        }

        vehicleEnterExitMapper.insertVehicleEnterExit(paramsMap);
        if (passFlag == 2 && paramsMap.get("enterId") != null)//如果是离开闸机，此条离开记录插入后，把ID更新到上次进入记录
        {
            Map<String, Object> enterParamsMap = new HashMap<>();
            String exitId = paramsMap.get("id").toString();
            enterParamsMap.put("exitId",exitId);
            enterParamsMap.put("id",paramsMap.get("enterId"));
            enterParamsMap.put("updateTime",paramsMap.get("passTime"));
            vehicleEnterExitMapper.updateVehicleEnterExit(enterParamsMap);
        }else  if (passFlag == 1 && paramsMap.get("exitId") != null)//如果是进入闸机，此条进入记录插入后，把ID更新到下次离开记录
        {
            Map<String, Object> exitParamsMap = new HashMap<>();
            String enterId = paramsMap.get("id").toString();
            exitParamsMap.put("enterId",enterId);
            exitParamsMap.put("id",paramsMap.get("exitId"));
            exitParamsMap.put("updateTime",paramsMap.get("passTime"));
            vehicleEnterExitMapper.updateVehicleEnterExit(exitParamsMap);
        }
        return true;
    }

    /**
     * 以进入记录为准，获取进入记录信息，如果此进入记录有对应的离开记录，同时匹配离开记录。如果没有离开记录，则对应的离开记录信息为null
     * @param params
     * @return
     */
    public List<Map<String, Object>> getVehicleEnterAndExitList(Map<String, Object> params) {
        String sortColumn = "SORT_TIME"; //默认的排序列
        String sortType = "DESC";
        String iSortCol_0 = (String) params.get("iSortCol_0");	//排序字段，前台传进来的为数值，列从0开始
        String sSortDir_0 = (String) params.get("sSortDir_0");	//排序类型，asc或desc
        if(StringUtil.isNotBlank(iSortCol_0) && StringUtil.isNotBlank(sSortDir_0)){
            sortColumn = (String) params.get("mDataProp_" + iSortCol_0);
            sortType = sSortDir_0;
        }
        String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
        PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
        List<Map<String, Object>>  enterExitList = getSqlSession().selectList("com.szgd.dao.ecdata.vehicle.VehicleEnterExitMapper.getVehicleEnterAndExitList", params,pageBounds);
        if (enterExitList != null && enterExitList.size() > 0)
        {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < enterExitList.size(); i++) {
                Map<String, Object> enterExitMap = enterExitList.get(i);
                String sEnterTime = enterExitMap.get("enterTime")==null?"":enterExitMap.get("enterTime").toString();
                String sExitTime = enterExitMap.get("exitTime")==null?"":enterExitMap.get("exitTime").toString();
                if (sExitTime == null || sExitTime.length() ==0)
                {
                    sExitTime = sd.format(new Date());
                }
                if (sEnterTime.length()  > 0 && sExitTime.length() > 0)
                {
                    long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
                    long nh = 1000 * 60 * 60;// 一小时的毫秒数
                    long nm = 1000 * 60;// 一分钟的毫秒数

                    long lEnterTime = 0;
                    long lExitTime = 0;
                    try {
                        lEnterTime = sd.parse(sEnterTime).getTime();
                        lExitTime = sd.parse(sExitTime).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long diff = lExitTime - lEnterTime;
                    long day = diff / nd;// 计算差多少天
                    long hour = diff % nd / nh + day * 24;// 计算差多少小时
                    long min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
                    String stayHours =  day + "天" + (hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分" ;
                    if (day==0)
                        stayHours = (hour - day * 24) + "时"
                                + (min - day * 24 * 60) + "分" ;
                    enterExitMap.put("stayHours",stayHours);
                }
            }
        }
        return enterExitList;
    }

    /**
     * 获取前N条进出记录
     * @param params
     * @return
     */
    public List<Map<String, Object>> getTopNVehicleEnterAndExitList(Map<String, Object> params) {
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            params.put("siteId",null);
        }

        List<Map<String,Object>> enterExitList = vehicleEnterExitMapper.getTopNVehicleEnterAndExitList(params);
        if (enterExitList != null)
        {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (int i = 0; i < enterExitList.size(); i++) {
                Map<String, Object> enterExitMap = enterExitList.get(i);
                String sEnterTime = enterExitMap.get("enterTime")==null?"":enterExitMap.get("enterTime").toString();
                String sExitTime = enterExitMap.get("exitTime")==null?"":enterExitMap.get("exitTime").toString();
                if (sEnterTime != null)
                {
                    enterExitMap.put("enterTime",sEnterTime.substring(0,16));
                }

                if (sExitTime == null || sExitTime.length() ==0)
                {
                    sExitTime = sd.format(new Date());
                }else
                {
                    enterExitMap.put("exitTime",sExitTime.substring(0,16));
                }
                if (sEnterTime.length()  > 0 && sExitTime.length() > 0)
                {
                    long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
                    long nh = 1000 * 60 * 60;// 一小时的毫秒数
                    long nm = 1000 * 60;// 一分钟的毫秒数

                    long lEnterTime = 0;
                    long lExitTime = 0;
                    try {
                        lEnterTime = sd.parse(sEnterTime).getTime();
                        lExitTime = sd.parse(sExitTime).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long diff = lExitTime - lEnterTime;
                    long day = diff / nd;// 计算差多少天
                    long hour = diff % nd / nh + day * 24;// 计算差多少小时
                    long min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟

                    String stayHours =  day + "天" + (hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分" ;
                    if (day==0)
                        stayHours =  (hour - day * 24) + "时"
                                + (min - day * 24 * 60) + "分" ;
                    /*String stayHours =  (day*24 + hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分";*/
                    enterExitMap.put("stayHours",stayHours);
                }

            }
        }
        return enterExitList;
    }


    /**
     * 获取前N条进出记录
     * @param params
     * @return
     */
    public List<Map<String, Object>> getTopNVehicleEnter_ExitList(Map<String, Object> params) {
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            params.put("siteId",null);
        }

        List<Map<String,Object>> enterExitList = vehicleEnterExitMapper.getTopNVehicleEnter_ExitList(params);
        if (enterExitList != null)
        {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (int i = 0; i < enterExitList.size(); i++) {
                Map<String, Object> enterExitMap = enterExitList.get(i);
                String sEnterTime = enterExitMap.get("enterTime")==null?"":enterExitMap.get("enterTime").toString();
                String sExitTime = enterExitMap.get("exitTime")==null?"":enterExitMap.get("exitTime").toString();
                if (sEnterTime.length() != 0)
                {
                    enterExitMap.put("enterTime",sEnterTime.substring(0,16));
                }

                if (sExitTime == null || sExitTime.length() ==0)
                {
                    sExitTime = sd.format(new Date());
                }else
                {
                    enterExitMap.put("exitTime",sExitTime.substring(0,16));
                }
                if (sEnterTime.length()  > 0 && sExitTime.length() > 0)
                {
                    long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
                    long nh = 1000 * 60 * 60;// 一小时的毫秒数
                    long nm = 1000 * 60;// 一分钟的毫秒数

                    long lEnterTime = 0;
                    long lExitTime = 0;
                    try {
                        lEnterTime = sd.parse(sEnterTime).getTime();
                        lExitTime = sd.parse(sExitTime).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long diff = lExitTime - lEnterTime;
                    long day = diff / nd;// 计算差多少天
                    long hour = diff % nd / nh + day * 24;// 计算差多少小时
                    long min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟

                    String stayHours =  day + "天" + (hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分" ;
                    if (day==0)
                        stayHours =  (hour - day * 24) + "时"
                                + (min - day * 24 * 60) + "分" ;
                    /*String stayHours =  (day*24 + hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分";*/
                    enterExitMap.put("stayHours",stayHours);
                }else
                {
                    enterExitMap.put("stayHours","");
                }

            }
        }
        return enterExitList;
    }


    /**
     * 除了返回getVehicleEnterAndExitList的结果，同时返回没有对应进入的离开记录
     * @param params
     * @return
     */
    public List<Map<String, Object>> getVehicleEnter_ExitList(Map<String, Object> params) {
        String sortColumn = "SORT_TIME"; //默认的排序列
        String sortType = "DESC";
        String iSortCol_0 = (String) params.get("iSortCol_0");	//排序字段，前台传进来的为数值，列从0开始
        String sSortDir_0 = (String) params.get("sSortDir_0");	//排序类型，asc或desc
        if(StringUtil.isNotBlank(iSortCol_0) && StringUtil.isNotBlank(sSortDir_0)){
            sortColumn = (String) params.get("mDataProp_" + iSortCol_0);
            sortType = sSortDir_0;
        }
        String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
        PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
        List<Map<String, Object>>  enterExitList = getSqlSession().selectList("com.szgd.dao.ecdata.vehicle.VehicleEnterExitMapper.getVehicleEnter_ExitList", params,pageBounds);
        if (enterExitList != null && enterExitList.size() > 0)
        {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < enterExitList.size(); i++) {
                Map<String, Object> enterExitMap = enterExitList.get(i);
                String sEnterTime = enterExitMap.get("enterTime")==null?"":enterExitMap.get("enterTime").toString();
                String sExitTime = enterExitMap.get("exitTime")==null?"":enterExitMap.get("exitTime").toString();
                if (sExitTime == null || sExitTime.length() ==0)
                {
                    sExitTime = sd.format(new Date());
                }
                if (sEnterTime.length()  > 0 && sExitTime.length() > 0)
                {
                    long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
                    long nh = 1000 * 60 * 60;// 一小时的毫秒数
                    long nm = 1000 * 60;// 一分钟的毫秒数

                    long lEnterTime = 0;
                    long lExitTime = 0;
                    try {
                        lEnterTime = sd.parse(sEnterTime).getTime();
                        lExitTime = sd.parse(sExitTime).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long diff = lExitTime - lEnterTime;
                    long day = diff / nd;// 计算差多少天
                    long hour = diff % nd / nh + day * 24;// 计算差多少小时
                    long min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
                    String stayHours =  day + "天" + (hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分" ;
                    if (day==0)
                        stayHours = (hour - day * 24) + "时"
                                + (min - day * 24 * 60) + "分" ;
                    enterExitMap.put("stayHours",stayHours);
                }else
                {
                    enterExitMap.put("stayHours","");
                }
            }
        }
        return enterExitList;
    }

    public List<Map<String, Object>> getEnterAndExitListNoPage(Map<String, Object> paramsMap) {
        List<Map<String,Object>> enterExitList = vehicleEnterExitMapper.getVehicleEnterAndExitList(paramsMap);
        if (enterExitList != null && enterExitList.size() > 0)
        {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < enterExitList.size(); i++) {
                Map<String, Object> enterExitMap = enterExitList.get(i);
                String sEnterTime = enterExitMap.get("enterTime")==null?"":enterExitMap.get("enterTime").toString();
                String sExitTime = enterExitMap.get("exitTime")==null?"":enterExitMap.get("exitTime").toString();
                if (sExitTime == null || sExitTime.length() ==0)
                {
                    sExitTime = sd.format(new Date());
                }
                if (sEnterTime.length()  > 0 && sExitTime.length() > 0)
                {
                    long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
                    long nh = 1000 * 60 * 60;// 一小时的毫秒数
                    long nm = 1000 * 60;// 一分钟的毫秒数

                    long lEnterTime = 0;
                    long lExitTime = 0;
                    try {
                        lEnterTime = sd.parse(sEnterTime).getTime();
                        lExitTime = sd.parse(sExitTime).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long diff = lExitTime - lEnterTime;
                    long day = diff / nd;// 计算差多少天
                    long hour = diff % nd / nh + day * 24;// 计算差多少小时
                    long min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
                    String stayHours =  day + "天" + (hour - day * 24) + "小时"
                            + (min - day * 24 * 60) + "分钟" ;
                    enterExitMap.put("stayHours",stayHours);
                }
            }
        }
        return enterExitList;
    }


    /**
     * 获取需要监理旁站的车辆的进入记录
     * @param paramsMap
     * @return
     */
    public List<Map<String, Object>> getOnSiteSuperviseVehicleEnterList(Map<String, Object> paramsMap) {
        List<Map<String, Object>> onSiteSuperviseVehicleEnterList = vehicleEnterExitMapper.getOnSiteSuperviseVehicleEnterList(paramsMap);
        return  onSiteSuperviseVehicleEnterList;
    }
    public int getVehicleEnterOrExitCount(String plateNumber,String passTime)
    {
        Map<String, Object> params = new HashMap<>();
        params.put("plateNumber",plateNumber);
        params.put("passTime",passTime);
        return  vehicleEnterExitMapper.getVehicleEnterOrExitCount(params);

    }

    public int getVehicleBePresentCount(Map<String, Object> params) {
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            params.put("siteId",null);
        }
        return  vehicleEnterExitMapper.getBePresentCount(params);
    }

    public Map<String, String> getFieldMap(){
        Map<String, String> fieldMapping = new LinkedHashMap<>();

//        fieldMapping.put("id","序号");
        fieldMapping.put("plateNumber","车牌号");
        fieldMapping.put("vehicleTypeName","车型");
        fieldMapping.put("inCharge","联系人");
        fieldMapping.put("enterTime","车辆进入时间");
        fieldMapping.put("exitTime","车辆离开时间");
        fieldMapping.put("stayHours","停留时长");
        fieldMapping.put("siteName","所属站点");

        return fieldMapping;
    }
}
